# OY 项目自动部署脚本
# 
# 前置条件：
# 1. 服务器上已安装 Nginx（运行 server-setup.sh）
# 2. 服务器上已配置 Nginx（上传 nginx.conf）
# 3. 已配置 SSH 密钥或准备输入密码
#
# 使用方法: .\deploy.ps1

$SERVER_IP = "154.219.117.72"  # 替换为你的服务器IP
$SERVER_USER = "root"           # 服务器用户名
$REMOTE_PATH = "/var/www/oy-promotion"

Write-Host "================================" -ForegroundColor Cyan
Write-Host "OY 推广项目自动部署" -ForegroundColor Green
Write-Host "================================" -ForegroundColor Cyan
Write-Host ""

# 检查服务器配置
if ($SERVER_IP -eq "your_server_ip") {
    Write-Host "[错误] 请先修改脚本中的 SERVER_IP 配置！" -ForegroundColor Red
    Write-Host "   编辑 deploy.ps1 文件，将 'your_server_ip' 替换为实际服务器IP" -ForegroundColor Yellow
    exit 1
}

Write-Host "部署配置：" -ForegroundColor Cyan
Write-Host "   服务器: $SERVER_USER@$SERVER_IP" -ForegroundColor White
Write-Host "   目标路径: $REMOTE_PATH" -ForegroundColor White
Write-Host ""

# 1. 构建项目
Write-Host "`n[1/5] 正在构建项目..." -ForegroundColor Yellow
npm run build

if ($LASTEXITCODE -ne 0) {
    Write-Host "[失败] 构建失败！" -ForegroundColor Red
    exit 1
}

Write-Host "[成功] 构建成功！" -ForegroundColor Green

# 2. 压缩 dist 目录
Write-Host "`n[2/5] 正在压缩文件..." -ForegroundColor Yellow
if (Test-Path "dist.zip") {
    Remove-Item "dist.zip"
}
Compress-Archive -Path dist\* -DestinationPath dist.zip

Write-Host "[成功] 文件压缩完成！" -ForegroundColor Green

# 3. 上传到服务器
Write-Host "`n[3/5] 正在上传到服务器..." -ForegroundColor Yellow
scp dist.zip ${SERVER_USER}@${SERVER_IP}:/tmp/

if ($LASTEXITCODE -ne 0) {
    Write-Host "[失败] 上传失败！" -ForegroundColor Red
    exit 1
}

Write-Host "[成功] 上传成功！" -ForegroundColor Green

# 4. 在服务器上解压并部署
Write-Host "`n[4/5] 正在服务器上部署..." -ForegroundColor Yellow
ssh ${SERVER_USER}@${SERVER_IP} @"
    sudo rm -rf ${REMOTE_PATH}/*
    sudo unzip -o /tmp/dist.zip -d ${REMOTE_PATH}/
    sudo chown -R nginx:nginx ${REMOTE_PATH}
    sudo chmod -R 755 ${REMOTE_PATH}
    sudo systemctl restart nginx
    rm /tmp/dist.zip
"@

if ($LASTEXITCODE -ne 0) {
    Write-Host "[失败] 部署失败！" -ForegroundColor Red
    exit 1
}

# 5. 清理本地临时文件
Remove-Item "dist.zip"

Write-Host "`n[成功] 部署完成！" -ForegroundColor Green
Write-Host "访问地址: http://${SERVER_IP}" -ForegroundColor Cyan
